import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

class TreeNode {
      int val;
      TreeNode left;
     TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }


  //二叉树的层序遍历
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        TreeNode node = root;
        queue.add(node);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list2 = new ArrayList<>();
            while (size != 0) {
                size--;
                TreeNode tmp = queue.remove();
                list2.add(tmp.val);
                if (tmp.left != null) {
                    queue.add(tmp.left);
                }
                if (tmp.right != null) {
                    queue.add(tmp.right);
                }
            }
            list.add(list2);
        }
        return reverse(list);

    }
    public List<List<Integer>> reverse(List<List<Integer>> list) {
        List<List<Integer>> tmp = new ArrayList<>();
        while (list != null) {
            tmp.add(list.remove(list.size()-1));
        }
        return tmp;
    }
    public static void main(String[] args) {

    }
}
